<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>分类: 技术教程 | 小小程序员</title><meta name="author" content="十一星野"><meta name="copyright" content="十一星野"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="在我们使用 MyBatis 的过程中，如果所有实体类和单表 CRUD 代码都需要手写，那将会是一件相当麻烦的事情。MyBatis 官方代码生成器 MyBatis Generator 可以帮助我们解决这个问题，在我的开源项目 mall 中也是使用的这个代码生成器，用习惯了也挺不错的。本文将介绍 MyBatis Generator 的使用方法及使用技巧，希望对大家有所帮助！  #简介MyBatis">
<meta property="og:type" content="article">
<meta property="og:title" content="解放双手！MyBatis官方代码生成工具给力！">
<meta property="og:url" content="https://ko25891wan.gitlab.io/2024/01/551cb439eb93.html">
<meta property="og:site_name" content="小小程序员">
<meta property="og:description" content="在我们使用 MyBatis 的过程中，如果所有实体类和单表 CRUD 代码都需要手写，那将会是一件相当麻烦的事情。MyBatis 官方代码生成器 MyBatis Generator 可以帮助我们解决这个问题，在我的开源项目 mall 中也是使用的这个代码生成器，用习惯了也挺不错的。本文将介绍 MyBatis Generator 的使用方法及使用技巧，希望对大家有所帮助！  #简介MyBatis">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png">
<meta property="article:published_time" content="2024-01-21T09:28:42.000Z">
<meta property="article:modified_time" content="2024-02-02T13:40:55.043Z">
<meta property="article:author" content="十一星野">
<meta property="article:tag" content="宅男,热血">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://ko25891wan.gitlab.io/2024/01/551cb439eb93.html"><link rel="preconnect" href="//fastly.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.5.1/css/all.min.css"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":1,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.staticfile.org/egjs-infinitegrid/4.11.0/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '分类: 技术教程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-02-02 21:40:55'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="小小程序员"><span class="site-name">小小程序员</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">解放双手！MyBatis官方代码生成工具给力！</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-01-21T09:28:42.000Z" title="发表于 2024-01-21 17:28:42">2024-01-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-02-02T13:40:55.043Z" title="更新于 2024-02-02 21:40:55">2024-02-02</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/">技术教程</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/">mall</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/%E5%8F%82%E8%80%83%E7%AF%87/">参考篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>17分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="解放双手！MyBatis官方代码生成工具给力！"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><blockquote>
<p>在我们使用 MyBatis 的过程中，如果所有实体类和单表 CRUD 代码都需要手写，那将会是一件相当麻烦的事情。MyBatis 官方代码生成器 MyBatis Generator 可以帮助我们解决这个问题，在我的开源项目 mall 中也是使用的这个代码生成器，用习惯了也挺不错的。本文将介绍 MyBatis Generator 的使用方法及使用技巧，希望对大家有所帮助！</p>
</blockquote>
<h2 id="简介"><a href="#简介" class="headerlink" title="#简介"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E7%AE%80%E4%BB%8B">#</a>简介</h2><p>MyBatis Generator（简称MBG）是MyBatis官方提供的代码生成工具。可以通过数据库表直接生成实体类、单表CRUD代码、mapper.xml文件，从而解放我们的双手！</p>
<h2 id="开始使用"><a href="#开始使用" class="headerlink" title="#开始使用"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8">#</a>开始使用</h2><blockquote>
<p>首先我们通过一个入门示例将MBG用起来，该示例会包含基础的CRUD操作。</p>
</blockquote>
<h3 id="集成MBG"><a href="#集成MBG" class="headerlink" title="#集成MBG"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E9%9B%86%E6%88%90mbg">#</a>集成MBG</h3><ul>
<li>在<code>pom.xml</code>中添加如下依赖，主要添加了MyBatis、PageHelper、Druid、MBG和MySQL驱动等依赖；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependencies&gt;</span><br><span class="line">    &lt;!--SpringBoot整合MyBatis--&gt;</span><br><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">        &lt;version&gt;2.1.3&lt;/version&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line">    &lt;!--MyBatis分页插件--&gt;</span><br><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;com.github.pagehelper&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;pagehelper-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">        &lt;version&gt;1.3.0&lt;/version&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line">    &lt;!--集成druid连接池--&gt;</span><br><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;com.alibaba&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;druid-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">        &lt;version&gt;1.1.10&lt;/version&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line">    &lt;!-- MyBatis 生成器 --&gt;</span><br><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;org.mybatis.generator&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;mybatis-generator-core&lt;/artifactId&gt;</span><br><span class="line">        &lt;version&gt;1.4.0&lt;/version&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line">    &lt;!--Mysql数据库驱动--&gt;</span><br><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;mysql&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;</span><br><span class="line">        &lt;version&gt;8.0.15&lt;/version&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line">&lt;/dependencies&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>在<code>application.yml</code>中对数据源和MyBatis的<code>mapper.xml</code>文件路径进行配置，这里做个约定，MBG生成的放在<code>resources/com/**/mapper</code>目录下，自定义的放在<code>resources/dao</code>目录下；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"># 数据源配置</span><br><span class="line">spring:</span><br><span class="line">  datasource:</span><br><span class="line">    url: jdbc:mysql://localhost:3306/mall?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai</span><br><span class="line">    username: root</span><br><span class="line">    password: root</span><br><span class="line"></span><br><span class="line"># MyBatis mapper.xml路径配置</span><br><span class="line">mybatis:</span><br><span class="line">  mapper-locations:</span><br><span class="line">    - classpath:dao/*.xml</span><br><span class="line">    - classpath*:com/**/mapper/*.xml</span><br></pre></td></tr></table></figure>

<ul>
<li>添加Java配置，用于扫码Mapper接口路径，这里还有个约定，MBG生成的放在<code>mapper</code>包下，自定义的放在<code>dao</code>包下。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * MyBatis配置类</span><br><span class="line"> * Created by macro on 2019/4/8.</span><br><span class="line"> */</span><br><span class="line">@Configuration</span><br><span class="line">@MapperScan(&#123;&quot;com.macro.mall.tiny.mbg.mapper&quot;,&quot;com.macro.mall.tiny.dao&quot;&#125;)</span><br><span class="line">public class MyBatisConfig &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="使用代码生成器"><a href="#使用代码生成器" class="headerlink" title="#使用代码生成器"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E4%BD%BF%E7%94%A8%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E5%99%A8">#</a>使用代码生成器</h3><ul>
<li>在使用MBG生成代码前，我们还需要对其进行一些配置，首先在<code>generator.properties</code>文件中配置好数据库连接信息；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">jdbc.driverClass=com.mysql.cj.jdbc.Driver</span><br><span class="line">jdbc.connectionURL=jdbc:mysql://localhost:3306/mall?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai</span><br><span class="line">jdbc.userId=root</span><br><span class="line">jdbc.password=root</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在<code>generatorConfig.xml</code>文件中对MBG进行配置，配置属性说明直接参考注释即可；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE generatorConfiguration</span><br><span class="line">        PUBLIC &quot;-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN&quot;</span><br><span class="line">        &quot;http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd&quot;&gt;</span><br><span class="line"></span><br><span class="line">&lt;generatorConfiguration&gt;</span><br><span class="line">    &lt;properties resource=&quot;generator.properties&quot;/&gt;</span><br><span class="line">    &lt;context id=&quot;MySqlContext&quot; targetRuntime=&quot;MyBatis3&quot; defaultModelType=&quot;flat&quot;&gt;</span><br><span class="line">        &lt;property name=&quot;beginningDelimiter&quot; value=&quot;`&quot;/&gt;</span><br><span class="line">        &lt;property name=&quot;endingDelimiter&quot; value=&quot;`&quot;/&gt;</span><br><span class="line">        &lt;property name=&quot;javaFileEncoding&quot; value=&quot;UTF-8&quot;/&gt;</span><br><span class="line">        &lt;!--生成mapper.xml时覆盖原文件--&gt;</span><br><span class="line">        &lt;plugin type=&quot;org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin&quot; /&gt;</span><br><span class="line">        &lt;!-- 为模型生成序列化方法--&gt;</span><br><span class="line">        &lt;plugin type=&quot;org.mybatis.generator.plugins.SerializablePlugin&quot;/&gt;</span><br><span class="line">        &lt;!-- 为生成的Java模型创建一个toString方法 --&gt;</span><br><span class="line">        &lt;plugin type=&quot;org.mybatis.generator.plugins.ToStringPlugin&quot;/&gt;</span><br><span class="line">        &lt;!--可以自定义生成model的代码注释--&gt;</span><br><span class="line">        &lt;commentGenerator type=&quot;com.macro.mall.tiny.mbg.CommentGenerator&quot;&gt;</span><br><span class="line">            &lt;!-- 是否去除自动生成的注释 true：是 ： false:否 --&gt;</span><br><span class="line">            &lt;property name=&quot;suppressAllComments&quot; value=&quot;true&quot;/&gt;</span><br><span class="line">            &lt;property name=&quot;suppressDate&quot; value=&quot;true&quot;/&gt;</span><br><span class="line">            &lt;property name=&quot;addRemarkComments&quot; value=&quot;true&quot;/&gt;</span><br><span class="line">        &lt;/commentGenerator&gt;</span><br><span class="line">        &lt;!--配置数据库连接--&gt;</span><br><span class="line">        &lt;jdbcConnection driverClass=&quot;$&#123;jdbc.driverClass&#125;&quot;</span><br><span class="line">                        connectionURL=&quot;$&#123;jdbc.connectionURL&#125;&quot;</span><br><span class="line">                        userId=&quot;$&#123;jdbc.userId&#125;&quot;</span><br><span class="line">                        password=&quot;$&#123;jdbc.password&#125;&quot;&gt;</span><br><span class="line">            &lt;!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题--&gt;</span><br><span class="line">            &lt;property name=&quot;nullCatalogMeansCurrent&quot; value=&quot;true&quot; /&gt;</span><br><span class="line">        &lt;/jdbcConnection&gt;</span><br><span class="line">        &lt;!--指定生成model的路径--&gt;</span><br><span class="line">        &lt;javaModelGenerator targetPackage=&quot;com.macro.mall.tiny.mbg.model&quot; targetProject=&quot;mall-tiny-generator\src\main\java&quot;/&gt;</span><br><span class="line">        &lt;!--指定生成mapper.xml的路径--&gt;</span><br><span class="line">        &lt;sqlMapGenerator targetPackage=&quot;com.macro.mall.tiny.mbg.mapper&quot; targetProject=&quot;mall-tiny-generator\src\main\resources&quot;/&gt;</span><br><span class="line">        &lt;!--指定生成mapper接口的的路径--&gt;</span><br><span class="line">        &lt;javaClientGenerator type=&quot;XMLMAPPER&quot; targetPackage=&quot;com.macro.mall.tiny.mbg.mapper&quot;</span><br><span class="line">                             targetProject=&quot;mall-tiny-generator\src\main\java&quot;/&gt;</span><br><span class="line">        &lt;!--生成全部表tableName设为%--&gt;</span><br><span class="line">        &lt;table tableName=&quot;ums_admin&quot;&gt;</span><br><span class="line">            &lt;generatedKey column=&quot;id&quot; sqlStatement=&quot;MySql&quot; identity=&quot;true&quot;/&gt;</span><br><span class="line">        &lt;/table&gt;</span><br><span class="line">        &lt;table tableName=&quot;ums_role&quot;&gt;</span><br><span class="line">            &lt;generatedKey column=&quot;id&quot; sqlStatement=&quot;MySql&quot; identity=&quot;true&quot;/&gt;</span><br><span class="line">        &lt;/table&gt;</span><br><span class="line">        &lt;table tableName=&quot;ums_admin_role_relation&quot;&gt;</span><br><span class="line">            &lt;generatedKey column=&quot;id&quot; sqlStatement=&quot;MySql&quot; identity=&quot;true&quot;/&gt;</span><br><span class="line">        &lt;/table&gt;</span><br><span class="line">        &lt;table tableName=&quot;ums_resource&quot;&gt;</span><br><span class="line">            &lt;generatedKey column=&quot;id&quot; sqlStatement=&quot;MySql&quot; identity=&quot;true&quot;/&gt;</span><br><span class="line">        &lt;/table&gt;</span><br><span class="line">        &lt;table tableName=&quot;ums_resource_category&quot;&gt;</span><br><span class="line">            &lt;generatedKey column=&quot;id&quot; sqlStatement=&quot;MySql&quot; identity=&quot;true&quot;/&gt;</span><br><span class="line">        &lt;/table&gt;</span><br><span class="line">    &lt;/context&gt;</span><br><span class="line">&lt;/generatorConfiguration&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>这里值得一提的是<code>targetRuntime</code>这个属性，设置不同的属性生成的代码和生成代码的使用方式会有所不同，常用的有<code>MyBatis3</code>和<code>MyBatis3DynamicSql</code>两种，这里使用的是<code>MyBatis3</code>；</p>
</li>
<li><p>如果你想自定义MBG生成的代码的话，可以自己写一个CommentGenerator来继承DefaultCommentGenerator，这里我自定义了实体类代码的生成，添加了Swagger注解的支持；</p>
</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line">package com.macro.mall.tiny.mbg;</span><br><span class="line"></span><br><span class="line">import org.mybatis.generator.api.IntrospectedColumn;</span><br><span class="line">import org.mybatis.generator.api.IntrospectedTable;</span><br><span class="line">import org.mybatis.generator.api.dom.java.CompilationUnit;</span><br><span class="line">import org.mybatis.generator.api.dom.java.Field;</span><br><span class="line">import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;</span><br><span class="line">import org.mybatis.generator.internal.DefaultCommentGenerator;</span><br><span class="line">import org.mybatis.generator.internal.util.StringUtility;</span><br><span class="line"></span><br><span class="line">import java.util.Properties;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 自定义注释生成器</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">public class CommentGenerator extends DefaultCommentGenerator &#123;</span><br><span class="line">    private boolean addRemarkComments = false;</span><br><span class="line">    private static final String EXAMPLE_SUFFIX=&quot;Example&quot;;</span><br><span class="line">    private static final String MAPPER_SUFFIX=&quot;Mapper&quot;;</span><br><span class="line">    private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME=&quot;io.swagger.annotations.ApiModelProperty&quot;;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 设置用户配置的参数</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public void addConfigurationProperties(Properties properties) &#123;</span><br><span class="line">        super.addConfigurationProperties(properties);</span><br><span class="line">        this.addRemarkComments = StringUtility.isTrue(properties.getProperty(&quot;addRemarkComments&quot;));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 给字段添加注释</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public void addFieldComment(Field field, IntrospectedTable introspectedTable,</span><br><span class="line">                                IntrospectedColumn introspectedColumn) &#123;</span><br><span class="line">        String remarks = introspectedColumn.getRemarks();</span><br><span class="line">        //根据参数和备注信息判断是否添加备注信息</span><br><span class="line">        if(addRemarkComments&amp;&amp;StringUtility.stringHasValue(remarks))&#123;</span><br><span class="line">            //数据库中特殊字符需要转义</span><br><span class="line">            if(remarks.contains(&quot;\&quot;&quot;))&#123;</span><br><span class="line">                remarks = remarks.replace(&quot;\&quot;&quot;,&quot;&#x27;&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            //给model的字段添加swagger注解</span><br><span class="line">            field.addJavaDocLine(&quot;@ApiModelProperty(value = \&quot;&quot;+remarks+&quot;\&quot;)&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void addJavaFileComment(CompilationUnit compilationUnit) &#123;</span><br><span class="line">        super.addJavaFileComment(compilationUnit);</span><br><span class="line">        //只在model中添加swagger注解类的导入</span><br><span class="line">        String fullyQualifiedName = compilationUnit.getType().getFullyQualifiedName();</span><br><span class="line">        if(!fullyQualifiedName.contains(MAPPER_SUFFIX)&amp;&amp;!fullyQualifiedName.contains(EXAMPLE_SUFFIX))&#123;</span><br><span class="line">            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>最后我们写个Generator类用于生成代码，直接运行main方法即可生成所有代码；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 用于生产MBG的代码</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">public class Generator &#123;</span><br><span class="line">    public static void main(String[] args) throws Exception &#123;</span><br><span class="line">        //MBG 执行过程中的警告信息</span><br><span class="line">        List&lt;String&gt; warnings = new ArrayList&lt;String&gt;();</span><br><span class="line">        //当生成的代码重复时，覆盖原代码</span><br><span class="line">        boolean overwrite = true;</span><br><span class="line">        //读取我们的 MBG 配置文件</span><br><span class="line">        InputStream is = Generator.class.getResourceAsStream(&quot;/generatorConfig.xml&quot;);</span><br><span class="line">        ConfigurationParser cp = new ConfigurationParser(warnings);</span><br><span class="line">        Configuration config = cp.parseConfiguration(is);</span><br><span class="line">        is.close();</span><br><span class="line"></span><br><span class="line">        DefaultShellCallback callback = new DefaultShellCallback(overwrite);</span><br><span class="line">        //创建 MBG</span><br><span class="line">        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);</span><br><span class="line">        //执行生成代码</span><br><span class="line">        myBatisGenerator.generate(null);</span><br><span class="line">        //输出警告信息</span><br><span class="line">        for (String warning : warnings) &#123;</span><br><span class="line">            System.out.println(warning);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>一切准备就绪，执行main方法，生成代码结构信息如下。</li>
</ul>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/mybatis_generator_start_01-6b33d423.png"></p>
<h3 id="实现基本的CRUD操作"><a href="#实现基本的CRUD操作" class="headerlink" title="#实现基本的CRUD操作"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E5%AE%9E%E7%8E%B0%E5%9F%BA%E6%9C%AC%E7%9A%84crud%E6%93%8D%E4%BD%9C">#</a>实现基本的CRUD操作</h3><blockquote>
<p>这里使用的是<code>mall-tiny</code>项目中权限管理功能相关表，具体可以参考<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/tN3zjoKQxg1U19D4Slih8w">《还在从零开始搭建项目？手撸了款快速开发脚手架！》open in new window</a>。</p>
</blockquote>
<ul>
<li>查看下MBG生成的Mapper接口，发现已经包含了基本的CRUD方法，具体SQL实现也已经在mapper.xml中生成了，单表CRUD直接调用对应方法即可；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public interface UmsAdminMapper &#123;</span><br><span class="line">    long countByExample(UmsAdminExample example);</span><br><span class="line"></span><br><span class="line">    int deleteByExample(UmsAdminExample example);</span><br><span class="line"></span><br><span class="line">    int deleteByPrimaryKey(Long id);</span><br><span class="line"></span><br><span class="line">    int insert(UmsAdmin record);</span><br><span class="line"></span><br><span class="line">    int insertSelective(UmsAdmin record);</span><br><span class="line"></span><br><span class="line">    List&lt;UmsAdmin&gt; selectByExample(UmsAdminExample example);</span><br><span class="line"></span><br><span class="line">    UmsAdmin selectByPrimaryKey(Long id);</span><br><span class="line"></span><br><span class="line">    int updateByExampleSelective(@Param(&quot;record&quot;) UmsAdmin record, @Param(&quot;example&quot;) UmsAdminExample example);</span><br><span class="line"></span><br><span class="line">    int updateByExample(@Param(&quot;record&quot;) UmsAdmin record, @Param(&quot;example&quot;) UmsAdminExample example);</span><br><span class="line"></span><br><span class="line">    int updateByPrimaryKeySelective(UmsAdmin record);</span><br><span class="line"></span><br><span class="line">    int updateByPrimaryKey(UmsAdmin record);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>生成代码中有一些Example类，比如UmsAdminExample，我们可以把它理解为一个条件构建器，用于构建SQL语句中的各种条件；</li>
</ul>
<p><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/mybatis_generator_start_02-c96ffde5.png"></p>
<ul>
<li>利用好MBG生成的代码即可完成单表的CRUD操作了，比如下面最常见的操作。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 后台用户管理Service实现类</span><br><span class="line"> * Created by macro on 2020/12/8.</span><br><span class="line"> */</span><br><span class="line">@Service</span><br><span class="line">public class UmsAdminServiceImpl implements UmsAdminService &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private UmsAdminMapper adminMapper;</span><br><span class="line">    @Autowired</span><br><span class="line">    private UmsAdminDao adminDao;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void create(UmsAdmin entity) &#123;</span><br><span class="line">        adminMapper.insert(entity);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void update(UmsAdmin entity) &#123;</span><br><span class="line">        adminMapper.updateByPrimaryKeySelective(entity);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void delete(Long id) &#123;</span><br><span class="line">        adminMapper.deleteByPrimaryKey(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public UmsAdmin select(Long id) &#123;</span><br><span class="line">        return adminMapper.selectByPrimaryKey(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public List&lt;UmsAdmin&gt; listAll(Integer pageNum, Integer pageSize) &#123;</span><br><span class="line">        PageHelper.startPage(pageNum, pageSize);</span><br><span class="line">        return adminMapper.selectByExample(new UmsAdminExample());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="进阶使用"><a href="#进阶使用" class="headerlink" title="#进阶使用"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E8%BF%9B%E9%98%B6%E4%BD%BF%E7%94%A8">#</a>进阶使用</h2><blockquote>
<p>想要用好MBG，上面的基础操作是不够的，还需要一些进阶的使用技巧。</p>
</blockquote>
<h3 id="条件查询"><a href="#条件查询" class="headerlink" title="#条件查询"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E6%9D%A1%E4%BB%B6%E6%9F%A5%E8%AF%A2">#</a>条件查询</h3><blockquote>
<p>使用Example类构建查询条件可以很方便地实现条件查询。</p>
</blockquote>
<ul>
<li>这里以按用户名和状态查询后台用户并按创建时间降序排列为例，SQL实现如下；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">SELECT</span><br><span class="line">	id,</span><br><span class="line">	username,</span><br><span class="line">	PASSWORD,</span><br><span class="line">	icon,</span><br><span class="line">	email,</span><br><span class="line">	nick_name,</span><br><span class="line">	note,</span><br><span class="line">	create_time,</span><br><span class="line">	login_time,</span><br><span class="line">STATUS </span><br><span class="line">FROM</span><br><span class="line">	ums_admin </span><br><span class="line">WHERE</span><br><span class="line">	( username = &#x27;macro&#x27; AND STATUS IN ( 0, 1 ) ) </span><br><span class="line">ORDER BY</span><br><span class="line">	create_time DESC;</span><br></pre></td></tr></table></figure>

<ul>
<li>对应的Java代码实现如下。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 后台用户管理Service实现类</span><br><span class="line"> * Created by macro on 2020/12/8.</span><br><span class="line"> */</span><br><span class="line">@Service</span><br><span class="line">public class UmsAdminServiceImpl implements UmsAdminService &#123;</span><br><span class="line">    </span><br><span class="line">    @Override</span><br><span class="line">    public List&lt;UmsAdmin&gt; list(Integer pageNum, Integer pageSize, String username, List&lt;Integer&gt; statusList) &#123;</span><br><span class="line">        PageHelper.startPage(pageNum, pageSize);</span><br><span class="line">        UmsAdminExample umsAdminExample = new UmsAdminExample();</span><br><span class="line">        UmsAdminExample.Criteria criteria = umsAdminExample.createCriteria();</span><br><span class="line">        if(StrUtil.isNotEmpty(username))&#123;</span><br><span class="line">            criteria.andUsernameEqualTo(username);</span><br><span class="line">        &#125;</span><br><span class="line">        criteria.andStatusIn(statusList);</span><br><span class="line">        umsAdminExample.setOrderByClause(&quot;create_time desc&quot;);</span><br><span class="line">        return adminMapper.selectByExample(umsAdminExample);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="子查询"><a href="#子查询" class="headerlink" title="#子查询"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E5%AD%90%E6%9F%A5%E8%AF%A2">#</a>子查询</h3><blockquote>
<p>使用MBG生成的代码并不能实现子查询，需要自己手写SQL实现。</p>
</blockquote>
<ul>
<li>这里以按角色ID查询后台用户为例，首先定义一个UmsAdminDao接口，这里约定下Dao里面存放的方法都是自定义SQL实现的方法，首先在Dao接口中添加<code>subList</code>方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Created by macro on 2020/12/9.</span><br><span class="line"> */</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line"></span><br><span class="line">    List&lt;UmsAdmin&gt; subList(@Param(&quot;roleId&quot;) Long roleId);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后创建一个UmsAdminDao.xml文件，对应UmsAdminDao接口的SQL实现，写好对应的SQL实现，注意使用的resultMap MBG已经帮我们生成好了，无需自己手写。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;subList&quot; resultMap=&quot;com.macro.mall.tiny.mbg.mapper.UmsAdminMapper.BaseResultMap&quot;&gt;</span><br><span class="line">    SELECT *</span><br><span class="line">    FROM ums_admin</span><br><span class="line">    WHERE id IN (SELECT admin_id FROM ums_admin_role_relation WHERE role_id = #&#123;roleId&#125;)</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<h3 id="Group和Join查询"><a href="#Group和Join查询" class="headerlink" title="#Group和Join查询"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#group%E5%92%8Cjoin%E6%9F%A5%E8%AF%A2">#</a>Group和Join查询</h3><blockquote>
<p>Group和Join查询也不能使用MBG生成的代码实现。</p>
</blockquote>
<ul>
<li>这里以按角色统计后台用户数量为例，首先在Dao接口中添加<code>groupList</code>方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line"></span><br><span class="line">    List&lt;RoleStatDto&gt; groupList();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在mapper.xml中添加对应的SQL实现，我们可以通过给查询出来的列起别名，直接把列映射到resultType所定义的对象中去。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;groupList&quot; resultType=&quot;com.macro.mall.tiny.domain.RoleStatDto&quot;&gt;</span><br><span class="line">    SELECT ur.id        AS roleId,</span><br><span class="line">           ur.NAME      AS roleName,</span><br><span class="line">           count(ua.id) AS count</span><br><span class="line">    FROM ums_role ur</span><br><span class="line">             LEFT JOIN ums_admin_role_relation uarr ON ur.id = uarr.role_id</span><br><span class="line">             LEFT JOIN ums_admin ua ON uarr.admin_id = ua.id</span><br><span class="line">    GROUP BY ur.id;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<h3 id="条件删除"><a href="#条件删除" class="headerlink" title="#条件删除"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E6%9D%A1%E4%BB%B6%E5%88%A0%E9%99%A4">#</a>条件删除</h3><blockquote>
<p>条件删除很简单，直接使用Example类构造删除条件即可。</p>
</blockquote>
<ul>
<li>这里以按用户名删除后台用户为例，SQL实现如下；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">DELETE </span><br><span class="line">FROM</span><br><span class="line">	ums_admin </span><br><span class="line">WHERE</span><br><span class="line">	username = &#x27;andy&#x27;;</span><br></pre></td></tr></table></figure>

<ul>
<li>对应Java中的实现为。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 后台用户管理Service实现类</span><br><span class="line"> * Created by macro on 2020/12/8.</span><br><span class="line"> */</span><br><span class="line">@Service</span><br><span class="line">public class UmsAdminServiceImpl implements UmsAdminService &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void deleteByUsername(String username) &#123;</span><br><span class="line">        UmsAdminExample example = new UmsAdminExample();</span><br><span class="line">        example.createCriteria().andUsernameEqualTo(username);</span><br><span class="line">        adminMapper.deleteByExample(example);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="条件修改"><a href="#条件修改" class="headerlink" title="#条件修改"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E6%9D%A1%E4%BB%B6%E4%BF%AE%E6%94%B9">#</a>条件修改</h3><blockquote>
<p>条件删除很简单，直接使用Example类构造修改条件，然后传入修改参数即可。</p>
</blockquote>
<ul>
<li>这里以按指定ID修改后台用户的状态为例，SQL实现如下；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">UPDATE ums_admin </span><br><span class="line">SET STATUS = 1 </span><br><span class="line">WHERE</span><br><span class="line">	id IN ( 1, 2 );</span><br></pre></td></tr></table></figure>

<ul>
<li>对应Java中的实现为。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 后台用户管理Service实现类</span><br><span class="line"> * Created by macro on 2020/12/8.</span><br><span class="line"> */</span><br><span class="line">@Service</span><br><span class="line">public class UmsAdminServiceImpl implements UmsAdminService &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void updateByIds(List&lt;Long&gt; ids, Integer status) &#123;</span><br><span class="line">        UmsAdmin record = new UmsAdmin();</span><br><span class="line">        record.setStatus(status);</span><br><span class="line">        UmsAdminExample example = new UmsAdminExample();</span><br><span class="line">        example.createCriteria().andIdIn(ids);</span><br><span class="line">        adminMapper.updateByExampleSelective(record,example);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="一对多查询"><a href="#一对多查询" class="headerlink" title="#一对多查询"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E4%B8%80%E5%AF%B9%E5%A4%9A%E6%9F%A5%E8%AF%A2">#</a>一对多查询</h3><blockquote>
<p>一对多查询无法直接使用MBG生成的代码实现，需要手写SQL实现，并使用resultMap来进行结果集映射。</p>
</blockquote>
<ul>
<li>这里以按ID查询后台用户信息（包含对应角色列表）为例，先在Dao接口中添加<code>selectWithRoleList</code>方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Created by macro on 2020/12/9.</span><br><span class="line"> */</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line"></span><br><span class="line">    AdminRoleDto selectWithRoleList(@Param(&quot;id&quot;) Long id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在mapper.xml中添加对应的SQL实现，这里有个小技巧，可以给角色表查询出来的列取个别名，添加一个<code>role_</code>前缀；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectWithRoleList&quot; resultMap=&quot;AdminRoleResult&quot;&gt;</span><br><span class="line">    SELECT ua.*,</span><br><span class="line">           ur.id          AS role_id,</span><br><span class="line">           ur.NAME        AS role_name,</span><br><span class="line">           ur.description AS role_description,</span><br><span class="line">           ur.create_time AS role_create_time,</span><br><span class="line">           ur.STATUS      AS role_status,</span><br><span class="line">           ur.sort        AS role_sort</span><br><span class="line">    FROM ums_admin ua</span><br><span class="line">             LEFT JOIN ums_admin_role_relation uarr ON ua.id = uarr.admin_id</span><br><span class="line">             LEFT JOIN ums_role ur ON uarr.role_id = ur.id</span><br><span class="line">    WHERE ua.id = #&#123;id&#125;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后定义一个叫做<code>AdminRoleResult</code>的ResultMap，通过<code>collection</code>标签直接将以<code>role_</code>开头的列映射到UmsRole对象中去即可。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;resultMap id=&quot;AdminRoleResult&quot; type=&quot;com.macro.mall.tiny.domain.AdminRoleDto&quot;</span><br><span class="line">           extends=&quot;com.macro.mall.tiny.mbg.mapper.UmsAdminMapper.BaseResultMap&quot;&gt;</span><br><span class="line">    &lt;collection property=&quot;roleList&quot; resultMap=&quot;com.macro.mall.tiny.mbg.mapper.UmsRoleMapper.BaseResultMap&quot;</span><br><span class="line">                columnPrefix=&quot;role_&quot;&gt;</span><br><span class="line">    &lt;/collection&gt;</span><br><span class="line">&lt;/resultMap&gt;</span><br></pre></td></tr></table></figure>

<h3 id="一对一查询"><a href="#一对一查询" class="headerlink" title="#一对一查询"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E4%B8%80%E5%AF%B9%E4%B8%80%E6%9F%A5%E8%AF%A2">#</a>一对一查询</h3><blockquote>
<p>一对一查询无法直接使用MBG生成的代码实现，需要手写SQL实现，并使用resultMap来进行结果集映射。</p>
</blockquote>
<ul>
<li>这里以按ID查询资源信息（包括分类信息）为例，先在Dao接口中添加<code>selectResourceWithCate</code>方法；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * Created by macro on 2020/12/9.</span><br><span class="line"> */</span><br><span class="line">public interface UmsAdminDao &#123;</span><br><span class="line"></span><br><span class="line">    ResourceWithCateDto selectResourceWithCate(@Param(&quot;id&quot;)Long id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后在mapper.xml中添加对应的SQL实现，可以给分类表查询出来的列取个别名，添加一个<code>cate_</code>前缀；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;select id=&quot;selectResourceWithCate&quot; resultMap=&quot;ResourceWithCateResult&quot;&gt;</span><br><span class="line">    SELECT ur.*,</span><br><span class="line">           urc.id          AS cate_id,</span><br><span class="line">           urc.`name`      AS cate_name,</span><br><span class="line">           urc.create_time AS cate_create_time,</span><br><span class="line">           urc.sort        AS cate_sort</span><br><span class="line">    FROM ums_resource ur</span><br><span class="line">             LEFT JOIN ums_resource_category urc ON ur.category_id = urc.id</span><br><span class="line">    WHERE ur.id = #&#123;id&#125;</span><br><span class="line">&lt;/select&gt;</span><br></pre></td></tr></table></figure>

<ul>
<li>然后定义一个叫做<code>ResourceWithCateResult</code>的ResultMap，通过<code>association</code>标签直接将以<code>cate_</code>开头的列映射到UmsResourceCategory对象中去即可。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;resultMap id=&quot;ResourceWithCateResult&quot; type=&quot;com.macro.mall.tiny.domain.ResourceWithCateDto&quot;</span><br><span class="line">           extends=&quot;com.macro.mall.tiny.mbg.mapper.UmsResourceMapper.BaseResultMap&quot;&gt;</span><br><span class="line">    &lt;association property=&quot;resourceCategory&quot;</span><br><span class="line">                 resultMap=&quot;com.macro.mall.tiny.mbg.mapper.UmsResourceCategoryMapper.BaseResultMap&quot;</span><br><span class="line">                 columnPrefix=&quot;cate_&quot;&gt;</span><br><span class="line">    &lt;/association&gt;</span><br><span class="line">&lt;/resultMap&gt;</span><br></pre></td></tr></table></figure>

<h2 id="总结"><a href="#总结" class="headerlink" title="#总结"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E6%80%BB%E7%BB%93">#</a>总结</h2><p>总的来说MyBatis官方代码生成器MBG还是很强大的，可以生成一些常用的单表CRUD方法，减少了我们的工作量。但是对于子查询、多表查询和一些复杂查询支持有点偏弱，依然需要在mapper.xml中手写SQL实现。</p>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="#参考资料"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99">#</a>参考资料</h2><p>官方文档：<a target="_blank" rel="noopener" href="https://mybatis.org/generator/index.html">https://mybatis.org/generator/index.html</a></p>
<h2 id="项目源码地址"><a href="#项目源码地址" class="headerlink" title="#项目源码地址"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/reference/mybatis_generator_start.html#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80">#</a>项目源码地址</h2><p><a target="_blank" rel="noopener" href="https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-generator">https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-generator</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io">十一星野</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io/2024/01/551cb439eb93.html">https://ko25891wan.gitlab.io/2024/01/551cb439eb93.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://ko25891wan.gitlab.io" target="_blank">小小程序员</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2024/01/c19ae8f7c9ad.html" title="居然有人想白嫖我的日志，赶紧开启安全保护压压惊！"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">居然有人想白嫖我的日志，赶紧开启安全保护压压惊！</div></div></a></div><div class="next-post pull-right"><a href="/2024/01/d9e47931d83a.html" title="还在手动整合Swagger？Swagger官方Starter是真的香！"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">还在手动整合Swagger？Swagger官方Starter是真的香！</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">十一星野</div><div class="author-info__description">归途也还可爱</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Gitlab"><i class="fab fa-gitlab" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:ko25891wan@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AE%80%E4%BB%8B"><span class="toc-number">1.</span> <span class="toc-text">简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%80%E5%A7%8B%E4%BD%BF%E7%94%A8"><span class="toc-number">2.</span> <span class="toc-text">开始使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9B%86%E6%88%90MBG"><span class="toc-number">2.1.</span> <span class="toc-text">集成MBG</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E5%99%A8"><span class="toc-number">2.2.</span> <span class="toc-text">使用代码生成器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0%E5%9F%BA%E6%9C%AC%E7%9A%84CRUD%E6%93%8D%E4%BD%9C"><span class="toc-number">2.3.</span> <span class="toc-text">实现基本的CRUD操作</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%9B%E9%98%B6%E4%BD%BF%E7%94%A8"><span class="toc-number">3.</span> <span class="toc-text">进阶使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9D%A1%E4%BB%B6%E6%9F%A5%E8%AF%A2"><span class="toc-number">3.1.</span> <span class="toc-text">条件查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AD%90%E6%9F%A5%E8%AF%A2"><span class="toc-number">3.2.</span> <span class="toc-text">子查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Group%E5%92%8CJoin%E6%9F%A5%E8%AF%A2"><span class="toc-number">3.3.</span> <span class="toc-text">Group和Join查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9D%A1%E4%BB%B6%E5%88%A0%E9%99%A4"><span class="toc-number">3.4.</span> <span class="toc-text">条件删除</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9D%A1%E4%BB%B6%E4%BF%AE%E6%94%B9"><span class="toc-number">3.5.</span> <span class="toc-text">条件修改</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E5%AF%B9%E5%A4%9A%E6%9F%A5%E8%AF%A2"><span class="toc-number">3.6.</span> <span class="toc-text">一对多查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E5%AF%B9%E4%B8%80%E6%9F%A5%E8%AF%A2"><span class="toc-number">3.7.</span> <span class="toc-text">一对一查询</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">4.</span> <span class="toc-text">总结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="toc-number">5.</span> <span class="toc-text">参考资料</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80"><span class="toc-number">6.</span> <span class="toc-text">项目源码地址</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/c60470b9a892.html" title="Java集合使用注意事项总结">Java集合使用注意事项总结</a><time datetime="2024-02-03T04:58:22.000Z" title="发表于 2024-02-03 12:58:22">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/81fb7a201f29.html" title="无题">无题</a><time datetime="2024-02-03T03:15:31.812Z" title="发表于 2024-02-03 11:15:31">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/5737c1ec69a9.html" title="Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)">Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)</a><time datetime="2024-01-31T06:56:16.000Z" title="发表于 2024-01-31 14:56:16">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/f510db7d2f19.html" title="Spring常见面试题总结">Spring常见面试题总结</a><time datetime="2024-01-31T06:55:58.000Z" title="发表于 2024-01-31 14:55:58">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/9be065e9f288.html" title="redis 面试">redis 面试</a><time datetime="2024-01-31T06:55:55.000Z" title="发表于 2024-01-31 14:55:55">2024-01-31</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By 十一星野</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.staticfile.org/instant.page/5.2.0/instantpage.min.js" type="module"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>